/*
 * Copyright 2018 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.codegen.core.impl;

import com.lap.codegen.core.FileManager;
import com.lap.codegen.domain.*;
import com.lap.codegen.exception.ManagerException;
import com.lap.codegen.utils.AnnotationUtils;
import com.lap.codegen.utils.Constants;
import com.lap.codegen.utils.FileUtils;
import com.lap.codegen.utils.FreemarkerUtils;
import freemarker.template.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <pre>
 *  文件处理
 * </pre>
 *
 * @author 劳水生 , 021(poker0325@me.com)
 * @version 1.0.0
 */
@Service("fileManager")
public class DefaultFileManager implements FileManager {
    private static final String DOC = "/";
    private static final String CONTEXT = "context";
    private static final String TABLE = "table";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private AtomicInteger i = new AtomicInteger(1);

    @Override
    public void writerFile(CodeContext context) throws ManagerException {
        Configuration cfg = null;
        try {
            String path = FileUtils.getRunPath() + "/template/";
            cfg = FreemarkerUtils.getFreemarker(path);
        } catch (Exception e) {
            throw new ManagerException(e);
        }
        initData(context, cfg);
        initDal(context, cfg);
        initService(context, cfg);
        initApi(context, cfg);
        this.initConfig(context, cfg);

        writeFile(context.getFileList());
    }

    /**
     * <pre>
     * 初始化配置
     * </pre>
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initConfig(CodeContext context, Configuration cfg) {
        List<Table> tableList = context.getTableList();
        if (Objects.nonNull(tableList) && !tableList.isEmpty()) {
            Map<String, Object> map = new HashMap<>(1);
            map.put(CONTEXT, context);

            CoreFile file = new CoreFile();
            context.getFileList().add(file);
            String content = FreemarkerUtils.getContent(cfg, Constants.FTL_TEMPLATE, map);
            file.setPath(FileUtils.getResources(null, null));
            file.setName("config.yml");
            file.setContent(content);
        }
    }

    /**
     * <pre>
     * 初始化数据模型
     * </pre>
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initData(CodeContext context, Configuration cfg) {
        List<Table> tableList = context.getTableList();
        if (Objects.nonNull(tableList) && !tableList.isEmpty()) {
            initAnnotation(context);
            ExtConf ext = context.getExt();
            PackageConf pc = context.getPackageConf();

            initJava(context, cfg, null, ext.getModelSuffix(), pc.getModel(), Constants.FTL_DOMAIN);
            initJava(context, cfg, null, ext.getParamSuffix(), pc.getParam(), Constants.FTL_PARAM);
            initJava(context, cfg, null, ext.getQuerySuffix(), pc.getQuery(), Constants.FTL_QUERY);
        }
    }

    /**
     * 初始化注解
     *
     * @param context 上线文
     */
    private void initAnnotation(CodeContext context) {
        CoreFile file = new CoreFile();
        context.getFileList().add(file);
        StringBuilder sb = new StringBuilder();

        context.getTableList().forEach(table -> {
            sb.append("##########\n");
            sb.append("#").append(table.getComment()).append("\n");
            sb.append("##########\n");
            if (Objects.nonNull(table.getDataList())) {
                table.getDataList().forEach(e -> {
                    if (e.isWriteDomain()) {
                        String content = AnnotationUtils.annotation(table.getUpperName(), e);
                        sb.append(content);
                    }
                });
            }
            sb.append("\n\n");
        });
        file.setPath(FileUtils.getResources(null, null));
        file.setName("ValidationMessages.properties");
        file.setContent(sb.toString());
    }

    /**
     * <pre>
     *  初始化JAVA文件
     * </pre>
     *
     * @param context     上下文信息
     * @param cfg         Freemarker 配置
     * @param prefix      JAVA 文件前缀
     * @param suffix      JAVA 文件后缀
     * @param packageName 扩展包,基础包都是在 basePackage里面
     */
    private void initJava(CodeContext context, Configuration cfg, String prefix, String suffix, String packageName, String ftl) {
        PackageConf pc = context.getPackageConf();
        context.getTableList().forEach(e -> {
            Map<String, Object> map = getStringObjectMap(context, e);

            CoreFile file = new CoreFile();
            file.setTable(e);
            String content = FreemarkerUtils.getContent(cfg, ftl, map);
            file.setName(FileUtils.getJavaFileName(prefix, e.getName(), suffix));
            file.setPath(FileUtils.getJavaPath("", pc.getBasePackage(), packageName));
            file.setContent(content);
            context.getFileList().add(file);
        });
    }

    /**
     * <pre>
     *  传入Freemarker文件的参数
     * </pre>
     *
     * @param context 上下文
     * @param e       表
     * @return Map
     */
    private Map<String, Object> getStringObjectMap(CodeContext context, Table e) {
        Map<String, Object> map = new HashMap<>(2);
        map.put(TABLE, e);
        map.put(CONTEXT, context);
        return map;
    }

    /**
     * 初始化数据库操作相关的信息
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initDal(CodeContext context, Configuration cfg) {
        List<Table> dataList = context.getTableList();
        if (Objects.nonNull(dataList) && !dataList.isEmpty()) {
            ExtConf ext = context.getExt();
            PackageConf pc = context.getPackageConf();
            initJava(context, cfg, ext.getDaoPrefix(), ext.getDaoSuffix(), pc.getDal(), Constants.FTL_MAPPER);
            initSource(context, cfg, ext.getXmlSuffix(), pc.getXml(), Constants.FTL_MAPPER_XML);
        }
    }

    /**
     * 初始化XML
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initSource(CodeContext context, Configuration cfg, String suffix, String packageName, String ftl) {
        context.getTableList().forEach(e -> {
            Map<String, Object> map = getStringObjectMap(context, e);

            CoreFile file = new CoreFile();
            file.setTable(e);
            String content = FreemarkerUtils.getContent(cfg, ftl, map);
            file.setName(FileUtils.getMapperName(e.getName(), suffix));
            file.setPath(FileUtils.getResources(null, packageName));
            file.setContent(content);
            context.getFileList().add(file);
        });
    }

    /**
     * 初始化业务代码
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initService(CodeContext context, Configuration cfg) {
        List<Table> tableList = context.getTableList();
        if (Objects.nonNull(tableList) && !tableList.isEmpty()) {
            ExtConf ext = context.getExt();
            PackageConf pc = context.getPackageConf();
            initJava(context, cfg, ext.getServicePrefix(), ext.getServiceSuffix(), pc.getService(), Constants.FTL_SERVICE_INTERFACE);
            //initJava(context, cfg, ext.getServicePrefix(), ext.getServiceSuffix(), getImpl(pc.getService()), Constants.FTL_SERVICE_IMPL);
            initJava(context, cfg, ext.getServiceImplPrefix(), ext.getServiceImplSuffix(), getImpl(pc.getService()), Constants.FTL_SERVICE_IMPL);
        }
    }

    /**
     * <pre>
     *
     * </pre>
     *
     * @param context 上下文信息
     * @param cfg     ftl配置
     */
    private void initApi(CodeContext context, Configuration cfg) {
        List<Table> tableList = context.getTableList();
        if (Objects.nonNull(tableList) && !tableList.isEmpty()) {
            ExtConf ext = context.getExt();
            PackageConf pc = context.getPackageConf();
            initJava(context, cfg, ext.getApiPrefix(), ext.getApiSuffix(), pc.getApi(), Constants.FTL_API);
        }
    }

    /**
     * 获取impl
     *
     * @param packageName 包
     * @return
     */
    private String getImpl(String packageName) {
        if (StringUtils.isNotBlank(packageName)) {
            return packageName + ".impl";
        } else {
            return "impl";
        }
    }

    /**
     * 输出文件
     *
     * @param fileList 属性
     */
    private void writeFile(List<CoreFile> fileList) {
        if (Objects.isNull(fileList)) {
            return;
        }
        long timestamp = System.currentTimeMillis();
        String basePath = FileUtils.getCurPath() + DOC + Constants.WRITER_OUT + DOC;
        for (CoreFile coreFile : fileList) {
            String path = basePath + coreFile.getPath();
            File file = new File(path);

            if (!file.exists()) {
                file.mkdirs();
            }
            logger.info("开始生成代码，目录是:{}", path);

            String filePath = path + coreFile.getName();

            boolean flag = true;
            File writeFile = new File(filePath);
            if (writeFile.exists()) {
                if (isSameFile(coreFile.getContent(), writeFile)) {
                    flag = false;
                    logger.warn("文件  {}  内容没有任何修改，无需重新生成!", writeFile);
                } else {
                    String bakFile = filePath + ".bak_" + timestamp;
                    File newFile = new File(bakFile);
                    boolean bakFlag = writeFile.renameTo(newFile);
                    logger.warn("文件已经存在，备份文件:{}，文件是: {}", bakFlag, bakFile);
                }
            }
            if (flag) {
                File newFile = new File(filePath);
                try (OutputStream out = new FileOutputStream(newFile); OutputStreamWriter writer = new OutputStreamWriter(out, "utf-8");) {

                    writer.write(coreFile.getContent());

                    logger.info("第{}个文件 :生成新的文件，文件是:{}", i.incrementAndGet(), filePath);
                    logger.info("文件内容:\n{}", coreFile.getContent());
                } catch (IOException e) {
                    logger.error("writeFile is error:{},{}", coreFile.getName(), e);
                }
            }
        }
    }

    /**
     * 判断文件的内容和字符串内容是否一样
     *
     * @param content 内容
     * @param file    文件
     * @return
     */
    private boolean isSameFile(String content, File file) {
        String fileMd5 = FileUtils.getFileMd5(file);
        String strMd5 = FileUtils.getStringMd5(content);
        logger.info("生成文件:Md5 {}, 存在文件:Md5 {}", strMd5, fileMd5);

        String fileSha1 = FileUtils.getFileSha1(file);
        String strSha1 = FileUtils.getStringSha1(content);
        logger.info("生成文件:Sha1 {}, 存在文件:Sha1 {}", strSha1, fileSha1);

        return (fileMd5 != null && fileMd5.equals(strMd5) && fileSha1 != null && strSha1.equals(fileSha1));
    }

}
